<?php

require_once(dirname(__FILE__) . '/../classes/Tick.php');

/**
 * Analog fot JavaScript setInterval
 * @staticvar Tick $tick
 * @param callback $function
 * @param float $time TIme in seconds
 */
function setInterval($function, $time) {
    static $tick = NULL;
    if (NULL === $tick) {
        $tick = Tick::getInstance();
    }

    $endTime = microtime(true) + $time;
    //$intervalId = array( new obj(array($endTime, $function, $time) ), 'callback');
    $intervalId = function(Event $event) use ($endTime, $function, $time) {
                static $nextTime = NULL;
                if (NULL == $nextTime) {
                    $nextTime = $endTime;
                }
                if (microtime(true) >= $nextTime) {
                    try {
                       call_user_func($function, $event->callee);
                    } catch (DieException $e) {
                        echo 'Caught exception: ', $e->getMessage(), "\n";
                    }
                    $nextTime = microtime(true) + $time;
                }
            };
    $tick->addEventListener('tick', $intervalId);
    return $intervalId;
}

/**
 * Analog fot JavaScript clearInterval
 * @staticvar Tick $tick
 * @param callback $timeoutId
 */
function clearInterval($intervalId) {
    static $tick = NULL;
    if (NULL === $tick) {
        $tick = Tick::getInstance();
    }
    $tick->removeEventListener('tick', $intervalId);
}